#!/bin/bash
########################################################################
# script name:  update_etc_profile.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2011/11/10    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -h               Hosts [all]
   -f               Files [comma seperated]

Ex.:
$0 -h all -f /etc/saunix.conf
$0 -h saprmt02,sapphs01 -f /etc/saunix.conf
STOP
}
if [ `whoami` != root ]; then
   echo Please run this script as root or using sudo
   exit
fi
#######################################
# Get parameters
#######################################
while getopts h:f: OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | sed 's/,/ /g' | sed 's/^-*//' | cut -d. -f1 | tr 'A-Z' 'a-z')
                ;;
	     f)
                FILES=$(echo $OPTARG | sed 's/,/ /g')
                ;;

        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
#######################################
# Variables and environnement
#######################################
SSH_OPTS=" -x -o ConnectTimeout=15 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=quiet"
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
#######################################
# MAIN
#######################################
NEWHOSTLIST=$(checkhost $HOSTS | grep -v Verifying)
for HOSTNAME in $NEWHOSTLIST
do
	#for FILE in $FILES
	#do
		a_FILE=$RANDOM.tar
		sudo /bin/gtar cPfh /tmp/$a_FILE $FILES && sudo chown saunix /tmp/$a_FILE
		/bin/echo "Scping file $a_FILE to $HOSTNAME:/tmp/$a_FILE: \c"
		sudo -u saunix scp -B -q /tmp/$a_FILE $HOSTNAME:/tmp/ || STATUS=fail /bin/echo failed
		if [[ "$STATUS" != "fail" ]]
		then
			echo "for i in $FILES; do if [[ -f \$i ]]; then cp -rp \$i \$i.`date +'%Y-%m-%d-%H-%M'` ; fi ; done; /bin/gtar xmpPf /tmp/$a_FILE && /bin/echo ok || /bin/echo failed ; rm /tmp/$a_FILE 2>&1 > /dev/null" | sudo -u saunix ssh $SSH_OPTS -T $HOSTNAME "cat | sudo /bin/bash"
		fi
		rm /tmp/$a_FILE 2>&1 > /dev/null
	#done
done
#######################################
exit 0

